//
//  ZClubDepartmentVC.m
//  WeClubs
//
//  Created by Zed Link on 28/4/2017.
//  Copyright © 2017 Zed. All rights reserved.
//

#import "ZClubDepartmentVC.h"
#import "ZMultiChosePanelCell.h"
#import "ZCommentHeader.h"
#import "ZClubPositionVC.h"
#import "ZResourceManager.h"
#import "ZDepartmentModel.h"

NSString * const ArchitectureCellReuseID = @"ZArchitectureCellReuseID";
NSString * const ArchitectureHeaderReuseID = @"ZClubArchitectureHeaderReuseID";

@interface ZClubDepartmentVC () <ZMultiChosePanelCellDelegate> {
    MBProgressHUD *_hud;
}

/** 组织部门数据源 */
@property (strong, nonatomic) NSMutableArray <ZDepartmentModel *> *departmentModels;
/** MultiChoseCell数据源 */
@property (strong, nonatomic) NSArray <ZMultiChoseModel *> *multiChoseModels;

@end

@implementation ZClubDepartmentVC

+ (instancetype)zNew
{
    return [self zNewGroup];
}

#pragma mark - About Navigation

- (void)zConfigNavigation
{
    [super zConfigNavigation];
    
    self.navigationItem.title = @"组织架构";
    if (self.type == ZClubDepartmentTypeCreate)
    {
        self.navigationItem.hidesBackButton = YES;
        self.navigationItem.rightBarButtonItem = [self zNavItemWithTitle:@"下一步" andSelector:@selector(finishBtnAction)];
    } else if (self.type == ZClubDepartmentTypeModify)
    {
        self.navigationItem.hidesBackButton = NO;
        [self zAddBackItemWithGesture:YES];
        self.navigationItem.rightBarButtonItem = [self zNavItemWithTitle:@"完成" andSelector:@selector(finishBtnAction)];
    }
}

- (void)finishBtnAction
{
    _hud = [MBProgressHUD zAlertProgress:@"正在配置组织部门"];
    
    // ========== 检测新添加部门, 原有部门 ==========
    NSMutableString *selectedDepartmentIds = [NSMutableString string];
    NSMutableString *newDepartmentNames = [NSMutableString string];
    
    for (ZDepartmentModel *department in self.departmentModels) {
        if (department.departmentId == 0 && department.isSelected == YES) {
            [newDepartmentNames appendFormat:@"%@,", department.departmentName];
        } else if (department.isSelected == YES) {
            [selectedDepartmentIds appendFormat:@"%ld,", department.departmentId];
        }
    }
    
    selectedDepartmentIds = [[self removeComma:selectedDepartmentIds] mutableCopy];
    newDepartmentNames = [[self removeComma:newDepartmentNames] mutableCopy];
    
    NSMutableDictionary *dataPara = [@{
                                       @"user_id" : @([ZUserInfo sharedInstance].userId),
                                       @"token" : [ZUserInfo sharedInstance].token,
                                       @"club_id" : self.clubId ,
                                       @"selected" : selectedDepartmentIds,
                                       } mutableCopy];
    
    if (newDepartmentNames != nil && [newDepartmentNames isEqualToString:@""] == NO) {
        [dataPara setObject:newDepartmentNames forKey:@"new_department"];
    }
    
    [HTTPRequest POST:kSetDepartmentURL parameter:dataPara success:^(id resposeObject) {
        [_hud hideAnimated:YES];
        
        if (self.type == ZClubDepartmentTypeModify)
        {

            [self.navigationController popViewControllerAnimated:YES];
        } else if (self.type == ZClubDepartmentTypeCreate)
        {
            ZClubPositionVC *vc = [ZClubPositionVC zNew];
            vc.clubId = self.clubId;
            [self.navigationController pushViewController:vc animated:YES];
        }
    } failure:^(NSError *error) {
        [_hud hideAnimated:YES];
        [MBProgressHUD zAlertToastMessage:@"请求配置组织部门失败, 请检查网络"];
    }];
    
}

#pragma mark - View Life Cycle

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    self.tableView.contentInset = UIEdgeInsetsMake(16, 0, 0, 0);
    self.tableView.bounces = NO;
    self.tableView.rowHeight = UITableViewAutomaticDimension;
    self.tableView.estimatedRowHeight = 100;
    
    [self.tableView registerNib:[UINib nibWithNibName:@"ZMultiChosePanelCell" bundle:nil] forCellReuseIdentifier:ArchitectureCellReuseID];
    [self.tableView registerClass:[ZCommentHeader class] forHeaderFooterViewReuseIdentifier:ArchitectureHeaderReuseID];
    
    _hud = [MBProgressHUD zAlertProgress:@"正在获取组织部门列表"];
    
    NSDictionary *dataPara = @{
                               @"user_id" : @([ZUserInfo sharedInstance].userId),
                               @"token" : [ZUserInfo sharedInstance].token,
                               @"club_id" : self.clubId,
                               @"pure_selected" : @(0),
                               };
    
    [HTTPRequest POST:kGetClubDepartmentURL parameter:dataPara success:^(id resposeObject) {
        [_hud hideAnimated:YES];
        
        NSArray *departments = resposeObject[@"data"][@"department"];
        NSMutableArray *tempArrM = [NSMutableArray arrayWithCapacity:departments.count];
        for (NSDictionary *dict in departments) {
            ZDepartmentModel *model = [[ZDepartmentModel alloc] initWithDictionary:dict];
            [tempArrM addObject:model];
        }
        self.departmentModels = tempArrM;
    } failure:^(NSError *error) {
        [MBProgressHUD zAlertToastMessage:@"获取失败!"];
    }];
}

#pragma mark - UITableViewDelegate & UITableViewDataSource

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    ZMultiChosePanelCell *cell = [tableView dequeueReusableCellWithIdentifier:ArchitectureCellReuseID];
    cell.delegate = self;
    cell.itemModels = self.multiChoseModels;
    
    return cell;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    ZCommentHeader *header = [tableView dequeueReusableHeaderFooterViewWithIdentifier:ArchitectureHeaderReuseID];
    header.alignment = ZTableHeaderAlignmentCenter;
    header.style = ZTableHeaderStyleSetting;
    [header zSetTitle:@"组织架构"];
    
    return  header;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return SETTING_STYLE_HEIGHT;
}

#pragma mark - ZMultiChosePanelCellDelegate

- (void)multiChosePanelCell:(ZMultiChosePanelCell *)cell didSelectedItem:(ZMultiChoseState)itemState AtIndex:(NSUInteger)index
{
    ZDepartmentModel *department = self.departmentModels[index];
    department.isSelected = itemState;
}

- (void)multiChosePanelCell:(ZMultiChosePanelCell *)cell didSelectedPlusItem:(UIButton *)plusItem
{
    Z_WEAK_SELF
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"添加新组织" message:nil preferredStyle:UIAlertControllerStyleAlert];
    [alert addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {
        [textField setPlaceholder:@"请输入组织名称"];
    }];
    
    [alert addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil]];
    [alert addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        UITextField *textField = alert.textFields.firstObject;
        
        ZDepartmentModel *model = [[ZDepartmentModel alloc] init];
        model.departmentName = textField.text;
        model.departmentId = 0;
        model.isSelected = 1;
        [weakSelf.departmentModels addObject:model];
        
        [weakSelf refreshDepartment];
    }]];
    
    [self.navigationController presentViewController:alert animated:YES completion:nil];
}

#pragma mark - Getter & Setter

- (void)refreshDepartment
{
    NSMutableArray *tempArrM = [NSMutableArray arrayWithCapacity:self.departmentModels.count];
    for (ZDepartmentModel *department in self.departmentModels) {
        ZMultiChoseModel *cellModel = [[ZMultiChoseModel alloc] init];
        cellModel.itemName = department.departmentName;
        cellModel.selected = department.isSelected;
        [tempArrM addObject:cellModel];
    }
    self.multiChoseModels = [NSArray arrayWithArray:tempArrM];
    [self.tableView reloadData];
}

- (void)setDepartmentModels:(NSMutableArray<ZDepartmentModel *> *)departmentModels
{
    _departmentModels = departmentModels;
    [self refreshDepartment];
}

#pragma mark - SEL
- (NSString *)removeComma:(NSString *)content
{
    if (content == nil || content.length == 0) {
        return content;
    }
    
    NSRange lastRange = NSMakeRange(content.length - 1, 1);
    NSString *comma = [content substringWithRange:lastRange];
    NSMutableString *temp = [NSMutableString stringWithString:content];
    if ([comma isEqualToString:@","]) {
        [temp deleteCharactersInRange:lastRange];
    }
    return [NSString stringWithString:temp];
}

@end
